package com.leyou.auth.config;

import com.leyou.auth.client.AuthClient;
import com.leyou.auth.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author 虎哥
 */
@Slf4j
@Configuration
@ConditionalOnProperty(prefix = "ly.auth", name = {"clientId", "secret"})
@EnableConfigurationProperties(ClientProperties.class)
public class AuthConfiguration {

    @Autowired
    private AuthClient authClient;

    @Bean
    public JwtUtils jwtUtils(ClientProperties prop) throws InterruptedException {
        while (true){
            try {
                // 远程调用，获取秘钥
                String key = authClient.getJwtKey(prop.getClientId(), prop.getSecret());
                log.info("JWT秘钥加载成功！");
                return new JwtUtils(key);
            } catch (Exception e) {
                log.error("JWT秘钥加载失败！10秒后重试。原因：", e);
                // 申请秘钥失败，需要重试,等待10秒
                Thread.sleep(10000);
            }
        }
    }
}
